package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){

        //判断验证码是否输入正确
        String validateCode = (String)map.get("validateCode");
        //从缓存中查是否有这条数据
        String code = jedisPool.getResource().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_ORDER);
        //判断是否正确
        if(validateCode !=null && code != null && validateCode.equals(code)){
            //验证码正确

            //把数据添加到数据库
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result submit = null;
            try {
                submit = orderService.submit(map);
            } catch (Exception e) {
                e.printStackTrace();
                return submit;
            }
            /*if(submit.isFlag()){
                //说明预约成功
                //发送短信提示
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,(String)map.get("telephone"),(String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }*/
            return submit;
        }else {
            //验证码错误给出提示
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }


    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
